package servlet.manager;

import net.sf.json.JSONObject;
import service.manager.ManagerService;
import service.manager.impl.ManagerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * ManagerLogin
 *
 * @author 谭文斌
 * @since 2023/8/29
 */
@WebServlet("/managerLogin")
public class ManagerLogin extends HttpServlet {
    ManagerService service=new ManagerServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset=utf8");

        PrintWriter out = resp.getWriter();
        String user = req.getParameter("user");
        String psw = req.getParameter("psw");
        // 设置响应map
        HashMap<String, Object> hashMap = new HashMap<>();
        String result= service.login(user, psw);
        if (result == "1" || result.equals("1")) {
            HttpSession session = req.getSession();
            session.setAttribute("manager", user);
            session.setAttribute("reader_first", "1");
            hashMap.put("code", 0);
            hashMap.put("msg", "登录成功");
            hashMap.put("url", req.getContextPath() + "/manager/01nav.jsp");
        } else {
            hashMap.put("code", 1);
            hashMap.put("msg", result);
        }
        JSONObject json = JSONObject.fromObject(hashMap);
        out.write(json.toString());
    }
}
